var title = "用户";
var config = {
    url_page: _dir + "userManager.html",
    url_add: _dir + "userManager_add.html",
    title_page: title + "查询",
    title_list: title + "列表",
    title_add: "添加" + title,
    title_edit: "修改" + title,
    code_list: "/userManager/query",
    code_delete: "/user/del",
    code_add: "/user/add",
    code_edit: "/user/update",
    code_dataUpload: "/files/upload",
    code_imgUpload: "/user/upload",
    pagination_01: $("#page_01"),
    share_list:'/user/share/query',
    jifen_list:'/userManager/integral/log',
    changeJifen:'/userManager/integral/update',
    getQuDao: "/channel/query",
    changeBeizhu:'/userManager/remark/update',
    changeInfo:'/userManager/update'
};
$(document).ready(function () {
    var defaultImg='../assets/defaultimg.jpg';
    if (_page == "userManager") {

        if($(".select2").length > 0){
            $(".select2").select2();
        }
        var pageNo = 1;
        setTitle_01(config['title_list'], config['title_page'], config['url_add']);
        // setDefaultDate($("#startTime"),$("#endTime"))
        //加载事件
        var _trs, _pageSize, _pageCount;
        var setData = function (pIndex, pSize) {
            pIndex = pIndex || 1;
            pSize = pSize || 20;
            var pageSetBody = { "pageNo": pIndex, "pageSize": pSize };
            var sendObj = {
                //   "shopName": $("#shopName").val(),
                "tel": $("#tel").val(),
                "nickname":$("#nickname").val(),
                "shopName":$("#shopName").val(),
                "shareCode":$("#shareCode").val(),
            };
            window.sessionStorage.setItem(_page+"data",JSON.stringify({
                'sendObj':sendObj,
                'pageSetBody':pageSetBody
            }));
            $.extend(sendObj,pageSetBody);
            _call(config['code_list'], sendObj, function (res) {
                _trs = "";
                if (!res.body || res.body.length == 0) {
                    _trs = "";
                    _pageSize = 1;
                    _pageCount = 1;
                    pageNo--
                    $("#table_01 tbody").html('');
                    d_alert('警告','没有更多数据啦！','warning')
                }
                else {
                    _pageSize = res.body.pageSize;
                    _pageCount = res.body.count;
                    $.each(res.body, function (i, v) {
                        _trs = _trs + `<tr>
                        <td  class="sequence">${dataIsNull(v['id'])}</td>
                        <td>
                        <input type="hidden" id="hiddenImg" value="${dataIsNull(v['headImg'])}">
                        <img style="width: 30px;height: 30px;" src="${v['headImg']?v['headImg']:defaultImg}" alt="">


                        </td>
                        <td style="cursor: pointer">${dataIsNull(v['tel'])}</td>
                        <td style="cursor: pointer">${dataIsNull(v['nickname'])}</td>
                        <td>${dataIsNull(v['isActivate'])==1?'已激活':'未激活'}</td>
                        <td style="cursor: pointer">${dataIsNull(v['integral'])}</td>
                        <td style="cursor: pointer">${dataIsNull(v['recommendCount'])}</td>

                        <td>${v['birth']?new Date(v['birth']).Format('yyyy-MM-dd'):'--'}</td>
                        <td style="cursor: pointer">${dataIsNull(v['sex'])==0?'女':'男'}</td>
                        <td style="cursor: pointer" dataAttr="${dataIsNull(v['channelId'])}">${dataIsNull(v['channelName'])}</td>
                        <td style="cursor: pointer;display:none">${dataIsNull(v['channelId'])}</td>
                        <td>${v['activateTime']?new Date(v['activateTime']).Format('yyyy-MM-dd'):'--'}</td>
                        <td>${v['lastLoginTime']?new Date(v['lastLoginTime']).Format('yyyy-MM-dd'):'--'}</td>
                        <td style="cursor: pointer">${dataIsNull(v['addr'])}</td>
                        <td style="cursor: pointer">${dataIsNull(v['shareCode'])}</td>
                        <td style="cursor:pointer" id="see">查看</td>
                        <td style="cursor: pointer" id="remarkModel">${dataIsNull(v['remark'])}</td>
                        <td>${getTdOperate('shareList', config['share_list'], v.id, "id", v.id)}</td>
                        </tr>`;
                    });
                    setPageData(res.body);
                    $("#table_01 tbody").html(_trs);

                }

                //绑定删除事件
                //  setDelete("id", config['code_delete']);

                //分页方法
            });
        };
        var loadingAll = function () {
            //初始化加载数据
            setData();
        }
        //积分模态框
        $('#table_01 ').on('click','#see',function () {
            $('#jifenModel').modal()
            var userid=$(this).parent().find('td').eq(0).text();
            var nowjifen=$(this).parent().find('td').eq(5).text()
            $('#integral').val(nowjifen)
            _call(config['jifen_list'], {id:userid}, function (res) {
                var ps=''
                $.each(res.body, function (i, v) {

                    ps = ps + `<li>
                    <p>${v.remark}</p>
                    </li>`;
                });
                $("#jifenHistory").html(ps);
            });

            $('#submitJifen').click(function () {
                var data={
                    id:userid,
                    integral:$('#integral').val()
                }
                urlSubmit(data)
            })
        })
        //备注模态框
        new setUpload(
            $("#idCardParent"),
            {
                'uploadUrl':config['code_dataUpload'],
                "urlDom":$("#headImg"),
                "fileInput":$("#fileInput")
            }
        );
        $('#table_01 ').on('click','#remarkModel',function () {
            var userid=$(this).parent().find('td').eq(0).text();
            $('#userremarkModel').modal()
            var nowjifen=$(this).text()
            $('#remark').val(nowjifen)
            $('#submitRemark').click(function () {
                var data={
                    id:userid,
                    remark:$('#remark').val()
                }
                changeRemark(data)
            })
        })




        $("#table_01 tbody").on('click','.change',function () {
            var defaultChannel=$(this).parent().parent().find('td').eq(9).text()
            var defaultChannelId=$(this).parent().parent().find('td').eq(9).attr('dataAttr')
            getQuDapAjax1(config['getQuDao'],'#channelId',{},defaultChannel,defaultChannelId,function () {
                $('.select2').change()
            })
            $('#userModel').modal()
            $('#gridSystemModalLabel').text($(this).parent().parent().find('td').eq(3).text())
            var userid=$(this).parent().parent().find('td').eq(0).text();
            $('#userModel #tel').val($(this).parent().parent().find('td').eq(2).text())
            $('#userModel #nickname').val($(this).parent().parent().find('td').eq(3).text())
            $('#userModel #sex').val($(this).parent().parent().find('td').eq(8).text()=='男' ? "1" : '0').trigger("change")
            $('#userModel #birth').val((new Date($(this).parent().parent().find('td').eq(7).text()).Format('yyyy-MM-dd')))
            $('#userModel #shareCode').val($(this).parent().parent().find('td').eq(14).text())
            $('#userModel #isActivate').val($(this).parent().parent().find('td').eq(4).text()=='已激活' ? "1" : '0').trigger("change")
            $('#userModel #headImg').val($(this).parent().parent().find('td').eq(1).find('input').val())
            $('#userModel #fileInput').val($(this).parent().parent().find('td').eq(1).find('input').val())
            var sexResult=$(this).parent().parent().find('td').eq(8).text()
            if(sexResult=='女'){
                sexResult=0
            }else{
                sexResult=1
            }

            $('#userModel #sex').trigger('change')
            var activeResult=$('#userModel #isActivate').val()


            if(activeResult=='未激活'){
                activeResult=0
            }else{
                activeResult=1
            }

            $('#changeInfo').click(function () {

                var data={
                    id:userid,
                    tel:$('#userModel #tel').val(),
                    nickname:$('#userModel #nickname').val(),
                    sex:$('#userModel #sex').val(),
                    birth:$('#userModel #birth').val()+' 00:00:00',
                    shareCode:$('#userModel #shareCode').val(),
                    headImg:$('#headImg').val()==''?'':$('#userModel #fileInput').val(),
                    isActivate:$('#userModel #isActivate').val(),
                    channelId:$('#userModel #channelId').val(),
                }
                _call(config['changeInfo'], data, function (res) {
                    var userManagerdata=pageNo
                    // var userManagerdata=sessionStorage.getItem('userManagerdata')

                    sessionStorage.clear()
                    if(res.code==1){
                        $("#userModel").modal('hide');

                    }else{
                        alert(res.info)
                    }
                    //setData(userManagerdata.pageSetBody.pageNo);
                    var loadingAll = function () {
                        //初始化加载数据
                        setData(userManagerdata);
                    }

                    loadingAll()

                });
                $("#changeInfo").unbind('click');
            })
        })
        autoSearchByCookie(loadingAll);
        //查询方法
        loadingAll();
        $(".homePage").click(function(){
            pageNo = 1
            setData(pageNo)
        })
        $(".prevPage").click(function(){
            if(pageNo > 1){
                pageNo--
                setData(pageNo)
            }else{
                d_alert("警告",'已经到头啦！','warning')
            }

        })
        $(".nextPage").click(function(){
            pageNo++
            setData(pageNo)
        })
        //查询方法
        setQuery(setData)
        //修改积分
        function urlSubmit(data){
            _call(config['changeJifen'], data, function (res) {
                if(res.code==1){
                    window.location.reload()
                }else{
                    alert('修改失败')
                }

            });
        }

        //修改备注
        function changeRemark(data){
            _call(config['changeBeizhu'], data, function (res) {
                if(res.code==1){
                    window.location.reload()
                }else{
                    alert('修改失败')
                }


            });
        }
    }
    else if (_page == "bookManage_add") {
        var sendObj2 = {};
        //初始化
        var PageInit = function () {
            var _fid = $.trim($.request.queryString["fid"]);
            var _fstaffNo = $.trim($.request.queryString["id"]);
            var _rtype = $.trim($.request.queryString["rtype"]);
            var _msgId = 0;
            this.get_fid = function () {
                return this._fid;
            };
            this.get_msgId = function () {
                return this._msgId;
            };
            this.set_fid = function (v) {
                this._fid = v;
            }
            this.set_msgId = function (v) {
                this._msgId = v;
            }
            this.setDefault = function (v) {
                if (_fid == "" && _fstaffNo == "" && _rtype == "") {
                    //添加
                    this.set_msgId(config['code_add']);
                    this.set_fid(0);
                    setTitle_02(config['title_add'],config['url_page']);
                    new setUpload($("#idCardParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#coverUrl"),'title':"封面",'responseUrl':"coverUrl"});
                    new setUpload($("#businessParent"),{'uploadUrl':config['code_imgUpload'],"urlDom":$("#downloadUrl")})
                }
                else if (_fid != "" && _fstaffNo != "" && _rtype == "edit") {
                    //修改
                    this.set_msgId(config['code_edit']);
                    this.set_fid(_fid);
                    setTitle_02(config['title_edit'],config['url_page']);
                    sendObj2['id'] = _fid;

                    if (getPageData(_fstaffNo)) {
                        var _v = getPageData(_fstaffNo);
                        var formObj = new Form();
                        formObj.init(_v);
                        new setUpload($("#idCardParent"),{'uploadUrl':config['code_dataUpload'],"urlDom":$("#coverUrl"),'title':"封面",'responseUrl':"coverUrl"});
                        new setUpload($("#businessParent"),{'uploadUrl':config['code_imgUpload'],"urlDom":$("#downloadUrl")});
                    }
                }

            }
        };
        var _default = new PageInit();
        _default.setDefault();

        //提交事件
        $(".validate-form .submit").on("click", function () {
            var _this = $(this);
            if ($(".validate-form").validate().form()) {
                sendObj2["bookCode"] = $("#bookCode").val();
                sendObj2["bookName"] = $("#bookName").val();
                sendObj2["bookDescribe"] = $("#bookDescribe").val();
                sendObj2["coverUrl"] = $("#coverUrl").val();
                sendObj2["downloadUrl"] = $("#downloadUrl").val();
                //   sendObj2["shareCode"] = $("#shareCode").val();
                _call(_default.get_msgId(), sendObj2, function (res) {
                    confirm_add_ok(res, config['url_page'], function () {
                        window.location.href = window.location.href;
                    });
                });

            }
        });
    }
    $(".select2").select2();
});
$(".select2").select2();
//排序 tableId: 表的id,iCol:第几列 ；dataType：iCol对应的列显示数据的数据类型
function sortAble(th, tableId, iCol, dataType) {
    var ascChar = "▲";
    var descChar = "▼";
    var table = document.getElementById(tableId);
    //排序标题加背景色
    for (var t = 0; t < table.tHead.rows[0].cells.length; t++) {
        var th = $(table.tHead.rows[0].cells[t]);
        var thText = th.html().replace(ascChar, "").replace(descChar, "");
        if (t == iCol) {
            th.css("background-color", "#ccc");
        }
        else {
            th.css("background-color", "#fff");
            th.html(thText);
        }
    }
    var tbody = table.tBodies[0];
    var colRows = tbody.rows;
    var aTrs = new Array;
    //将得到的行放入数组，备用
    for (var i = 0; i < colRows.length; i++) {
        //注：如果要求“分组明细不参与排序”，把下面的注释去掉即可
        //if ($(colRows[i]).attr("group") != undefined) {
        aTrs.push(colRows[i]);
        //}
    }
    //判断上一次排列的列和现在需要排列的是否同一个。
    var thCol = $(table.tHead.rows[0].cells[iCol]);
    if (table.sortCol == iCol) {
        aTrs.reverse();
    } else {
        //如果不是同一列，使用数组的sort方法，传进排序函数
        aTrs.sort(compareEle(iCol, dataType));
    }
    var oFragment = document.createDocumentFragment();
    for (var i = 0; i < aTrs.length; i++) {
        oFragment.appendChild(aTrs[i]);
    }
    tbody.appendChild(oFragment);
    //记录最后一次排序的列索引
    table.sortCol = iCol;
    //给排序标题加“升序、降序” 小图标显示
    var th = $(table.tHead.rows[0].cells[iCol]);
    if (th.html().indexOf(ascChar) == -1 && th.html().indexOf(descChar) == -1) {
        th.html(th.html() + ascChar);
    }
    else if (th.html().indexOf(ascChar) != -1) {
        th.html(th.html().replace(ascChar, descChar));
    }
    else if (th.html().indexOf(descChar) != -1) {
        th.html(th.html().replace(descChar, ascChar));
    }
    //重新整理分组
    var subRows = $("#" + tableId + " tr[parent]");
    for (var t = subRows.length - 1; t >= 0 ; t--) {
        var parent = $("#" + tableId + " tr[group='" + $(subRows[t]).attr("parent") + "']");
        parent.after($(subRows[t]));
    }
}
//将列的类型转化成相应的可以排列的数据类型
function convert(sValue, dataType) {
    switch (dataType) {
        case "int":
            return parseInt(sValue, 10);
        case "float":
            return parseFloat(sValue);
        case "date":
            return new Date(Date.parse(sValue));
        case "string":
        default:
            return sValue.toString();
    }
}
//排序函数，iCol表示列索引，dataType表示该列的数据类型
function compareEle(iCol, dataType) {
    return function (oTR1, oTR2) {
        var vValue1 = convert(removeHtmlTag($(oTR1.cells[iCol]).html()), dataType);
        var vValue2 = convert(removeHtmlTag($(oTR2.cells[iCol]).html()), dataType);
        if (vValue1 < vValue2) {
            return -1;
        }
        else {
            return 1;
        }
    };
}
//去掉html标签
function removeHtmlTag(html) {
    return html.replace(/<[^>]+>/g, "");
}

//点击分组行时，切换分组明细的显示/隐藏
function showSub(a) {
    var groupValue = $(a).parent().parent().attr("group");
    var subDetails = $("tr[parent='" + groupValue + "']");
    subDetails.toggle();
}